package archforce.atp.x.ssh.tool;

import archforce.atp.x.ssh.entity.JumpMappingConfig;
import archforce.atp.x.ui.impl.common.model.PanelDataModel;

import java.io.*;

/**
 * @author wx
 * @version 1.0
 * @date 2022/4/27 12:02
 */
public class PersistenceConfigTool {

    private static final String ConfigFile = "config.cfg";

    public static JumpMappingConfig loadJumpMapping() throws IOException, ClassNotFoundException {
        return (JumpMappingConfig) load();
    }

    public static PanelDataModel loadPanelData() throws IOException, ClassNotFoundException {
        return (PanelDataModel) load();
    }

    public static Object load() throws IOException, ClassNotFoundException {
        String appPath = AppPathTool.getAppPath(PersistenceConfigTool.class);
        String filePath = appPath + File.separator + ConfigFile;
        File file = new File(filePath);
        System.out.println("load path:" + filePath);
        if(!file.exists() || file.length() <= 0){
            file.createNewFile();
            return null;
        }
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
        Object data = inputStream.readObject();
        return data;
    }

    public static boolean persistenceJumpMappingData(JumpMappingConfig data) throws IOException {
        return persistence(data);
    }

    public static boolean persistencePanelData(PanelDataModel data) throws IOException {
        return persistence(data);
    }

    private static boolean persistence(Object data) throws IOException {
        if(data == null){
            return false;
        }
        String appPath = AppPathTool.getAppPath(PersistenceConfigTool.class);
        String filePath = appPath + File.separator + ConfigFile;
        System.out.println("persistence path:" + filePath);
        File file = new File(filePath);
        if(!file.exists()){
            file.createNewFile();
        }
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file, false));
        objectOutputStream.writeObject(data);
        return true;
    }
}
